﻿using Pay.Data;
using Pay.DTO;
using Pay.IService;
using Pay.Service.Cache;
using Pay.TO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pay.Service {
    public class TokenShopSubjectService : ServiceBase, ITokenShopSubjectService, IDisposable {
        private IUnitOfWork _iUnitOfWork;
        private IProductActivityService _iProductActivityService;
        public TokenShopSubjectService(IUnitOfWork iUnitOfWork, IProductActivityService iProductActivityService) : base(iUnitOfWork) {
            _iUnitOfWork = iUnitOfWork;
            _iProductActivityService = iProductActivityService;
        }

        /// <summary>
        /// 获得商城专题列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedResult<token_shop_subject_dto> GetTokenShopSubjects(TokenShopSubjectQuery query) {
            var filter = PredicateBuilder.True<TokenShopSubject>();
            if (!string.IsNullOrEmpty(query.title)) {
                filter = filter.And(c => c.Title == query.title);
            }
            if (!string.IsNullOrEmpty(query.status)) {
                int value = int.Parse(query.status);
                filter = filter.And(c => c.Status == (ETokenShopSubjectStatus)value);
            }
            if (!string.IsNullOrEmpty(query.begin_time)) {
                DateTime time = DateTime.Parse(query.begin_time);
                filter = filter.And(c => c.CreateTime >= time);
            }
            if (!string.IsNullOrEmpty(query.end_time)) {
                DateTime time = DateTime.Parse(query.end_time).AddDays(1);
                filter = filter.And(c => c.CreateTime <= time);
            }
            var result = context.TokenShopSubject.FromCachePaged<TokenShopSubject, token_shop_subject_dto>(query.page, query.size, filter, orderBy => orderBy.OrderBy(o => o.Sort));
            return result;
        }

        /// <summary>
        /// 获得专题
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public token_shop_subject_dto GetTokenShopSubject(long id) {
            return context.TokenShopSubject.Where(c => c.Id == id).FromCacheFirstOrDefault<TokenShopSubject, token_shop_subject_dto>("TokenShopSubject");
        }

        /// <summary>
        /// 新增或修改专题
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public bool AddOrUpdate(token_shop_subject_dto dto) {
            if (dto.id == 0) {//新增
                TokenShopSubject model = new TokenShopSubject();
                dto.ToDtoObject(model);
                model.CreateTime = DateTime.Now;
                context.TokenShopSubject.Add(model);
                return _iUnitOfWork.Commit() > 0;
            } else {//修改
                TokenShopSubject model = context.TokenShopSubject.FindById(dto.id);
                dto.ToDtoObject(model);
                return _iUnitOfWork.Commit("TokenShopSubject") > 0;
            }
        }

        /// <summary>
        /// 修改专题状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public bool UpdateTokenShopSubjectStatus(long id, int status) {
            TokenShopSubject model = context.TokenShopSubject.FindById(id);
            model.Status = (ETokenShopSubjectStatus)(status);
            return _iUnitOfWork.Commit("TokenShopSubject") > 0;
        }

        /// <summary>
        /// 获取对应专题商品
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedResult<token_shop_subject_product_dto> GetSubjectProducts(TokenShopSubjectProductQuery query) {
            var filter = PredicateBuilder.True<TokenShopSubjectProduct>();
            if (query.subject_id > 0) {
                filter = filter.And(c => c.SubjectId == query.subject_id);
            }
            if (!string.IsNullOrEmpty(query.product_name)) {
                filter = filter.And(c => c.Product.Name.Contains(query.product_name));
            }
            filter = filter.And(c => c.Product.Stock > 0 && c.Product.SaleStatus == SaleStatus.Sell && c.Product.AuditStatus == AuditStatus.Sell && c.Product.Type != 5);
            var result = context.TokenShopSubjectProduct.FromCachePaged<TokenShopSubjectProduct, token_shop_subject_product_dto>(query.page, query.size, filter, orderBy => orderBy.OrderByDescending(o => o.Sort).ThenByDescending(o => (query.conditions == 0 ? o.Product.UpdateTime : query.conditions == 1 ? o.Product.SaleCount : o.Product.CreateTime)), "TokenShopSubjectProduct" + query.subject_id);
          
            //产品活动处理
            if(result.rows != null && result.rows.Count() > 0) {
                foreach(var row in result.rows) {
                    row.product = _iProductActivityService.ProductActivityHandle(row.product);
                }
            }

            //浏览量添加
            if (query.pageviews_num) {
                var model = context.TokenShopSubject.FindById(query.subject_id);
                model.PageviewsNum++;
                _iUnitOfWork.Commit();
            }
            return result;
        }

        /// <summary>
        /// 专题添加商品
        /// </summary>
        /// <param name="product_dtos"></param>
        /// <returns></returns>
        public bool AddProducts(List<token_shop_subject_product_dto> product_dtos) {
            foreach (var product_dto in product_dtos) {
                product_dto.create_time = DateTime.Now;
                context.TokenShopSubjectProduct.Add(product_dto.ToDtoObject<TokenShopSubjectProduct>());
            }

            return _iUnitOfWork.Commit() > 0;

        }

        /// <summary>
        /// 该专题是否存在该商品
        /// </summary>
        /// <param name="product_id"></param>
        /// <returns></returns>
        public bool SubjectProductExist(long subject_id, long product_id) {
            return context.TokenShopSubjectProduct.Where(c => c.SubjectId == subject_id && c.ProductId == product_id).Count() > 0;
        }

        /// <summary>
        /// 删除对应专题商品
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DeleteProduct(long id) {
            var subjectId = context.TokenShopSubjectProduct.FindById(id).SubjectId;
            context.TokenShopSubjectProduct.Remove(id);
            context.TokenShopSubject.FindById(subjectId).ProductNum--;
            return _iUnitOfWork.Commit("TokenShopSubjectProduct" + subjectId) > 0;
        }

        /// <summary>
        /// 修改商品排序
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool AlterSort(token_shop_subject_product_dto dto) {
            var model = context.TokenShopSubjectProduct.FindById(dto.id);
            model.Sort = dto.sort;
            return _iUnitOfWork.Commit("TokenShopSubjectProduct" + model.SubjectId) > 0;
        }

        /// <summary>
        /// 统计商品数
        /// </summary>
        public bool CountProducts(long subject_id) {
            var model = context.TokenShopSubject.FindById(subject_id);
            model.ProductNum = context.TokenShopSubjectProduct.Where(c => c.SubjectId == subject_id).Count();
            return _iUnitOfWork.Commit() > 0;
        }

        #region H5专题
        /// <summary>
        /// 获取H5专题列表
        /// </summary>
        /// <returns></returns>
        public List<token_shop_subject_dto> GetTokenShopSubjects(ETokenShopSubjectType type) {
            return context.TokenShopSubject.Where(c => c.Status == ETokenShopSubjectStatus.Normal && (c.Type == type || c.Type == ETokenShopSubjectType.Fixed))
                                           .OrderBy(c => c.Sort).FromCache<TokenShopSubject, token_shop_subject_dto>("TokenShopSubject");
        }
        #endregion
    }
}
